<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>广告管理</title>
    <link rel="stylesheet" href="/static/lib/layui-v2.5.6/layui-v2.5.6/layui/css/layui.css">
    <style>
        .layui-table-cell{
            height:50px;
            line-height: 50px;
        }
        .btn-box {
            position: relative;
        }

        .file-ipt {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0; 
        }

        .btn {
            width: 100px;
            height: 30px;
            background-color: skyblue;
            color: white;
            margin-right: 80px;
            border: none;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <table id="demo" lay-filter="test"></table>


    
    <div id="advertisementUpdate" style="display: none;margin-top: 30px;">
        <form class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">广告名称</label>
                <div class="layui-input-inline">
                    <input id="advertisement_name" type="text" name="password" required lay-verify="required" placeholder="请输入广告名" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item btn-box" style="margin: 30px 0 0 30px;">
                <button class="btn">上传图片</button>
                <input type="file" id="imgPath" class="file-ipt">
            </div>
        </form>
    </div>

    <script type="text/html" id="barDemo">
        <i class="layui-icon layui-icon-list" lay-event="advertisementUpdate" title="广告详细"></i>
        <i class="layui-icon layui-icon-delete" lay-event="advertisementDel" title="广告删除"></i>
        <i class="layui-icon layui-icon-upload-circle" lay-event="advertisementDelStatus" title="广告状态改变"></i>
    </script>

    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm layui-btn-radius" lay-event="advertisementAdd">添加广告</button>
        </div>
    </script>

    <script type="text/html" id="titleTpl">
        {{#  if(d.id < 100){ }}
          <a href="/detail/{{d.id}}" class="layui-table-link">{{d.title}}</a>
        {{#  } else { }}
          {{d.title}}(普通用户)
        {{#  } }}
    </script>

    <script type="text/html" id="createtimeTpl">
          {{layui.util.toDateString(Number(d.create_time), 'yyyy.MM.dd HH:mm:ss')}}
    </script>

    <script src="../lib/layui-v2.5.6/layui-v2.5.6/layui/layui.js"></script>
    
    <script>
        layui.use('table', function(){
            var $ = layui.jquery;
            var table = layui.table;
            // var util = layui.util;


            table.render({
                elem: '#demo',
                height: 'full-60',
                url: '/admin/advertisement/query', //数据接口
                page: {layout: ['prev', 'page', 'next', 'skip', 'count']}, //开启分页
                toolbar: '#toolbarDemo',
                defaultToolbar: [],
                id: 'adTest',
                cols: [[ //表头
                {field: 'advertisement_name', title: '广告名称', width:'15%', sort: true, fixed: 'left'},
                {field: 'pic_url', title: '广告图片', width:'20%',  templet:'<div><img src="https://vm.fowotek.com{{d.pic_url}}" </div>'},
                {field: 'begin_time', title: '开始时间', templet:  "<div>{{layui.util.toDateString(Number(d.begin_time), 'yyyy.MM.dd HH:mm:ss')}}</div>", width:'15%', sort: true},
                {field: 'create_time', title: '创建时间', templet:"<div>{{layui.util.toDateString(Number(d.create_time), 'yyyy.MM.dd HH:mm:ss')}}</div>", width:'15%'} ,
                {field: 'usage_time', title: '投放时长', templet:'<div>{{ MillisecondToDate(d.usage_time) }}</div>', width: '15%'},
                {field: 'status', title: '广告状态', width: '10%', templet:'<div>{{adStatus(d.status)}}</div>', sort: true},
                {fixed: 'right', width:'10%', align:'center', toolbar: '#barDemo'}
                ]],


                parseData: function(res){ //res 即为原始返回的数据
                    console.log(res.data.list)
                    return {
                    "code": res.success, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                    };
                },
                // request: {
                //     pageName: 'curr' //页码的参数名称，默认：page
                //     ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
                // },
                response: {
                    // statusName: 'success', //规定数据状态的字段名称，默认：code
                    statusCode: true //规定成功的状态码，默认：0
                }
            });
        
            table.on('toolbar(test)', function(obj){
                switch(obj.event){
                    case 'advertisementAdd':   
                        $("#imgPath").val('')
                        $("#advertisement_name").val('')
                        layer.open({
                            type: 1,
                            skin: 'layui-layer-rim', //加上边框
                            area: ['500px', '300px'], //宽高
                            title: '广告信息添加',
                            btn: ['添加','取消'],
                            content: $('#advertisementUpdate'),
                            yes: function(index){
                                // console.log($("#advertisement_name").val())
                                // var advertisement_name = $("#advertisement_name").val()
                                var file = $("#imgPath")[0].files[0];//获取文件
                                var formData = new FormData();
                                if (file == undefined) {
                                    layer.msg('选择上传图片')
                                }else {
                                    formData.append("picture", file);
                                    formData.append("advertisement_name", $("#advertisement_name").val());
                                    $.ajax({
                                        type: "post",
                                        url: "/admin/advertisement/addAdvertisement",
                                        data: formData,
                                        dataType: "json",
                                        processData: false,
                                        contentType: false,
                                        success: function(mag){
                                            layer.msg(mag.message)
                                            table.reload('adTest')
                                        }
                                    })
                                    layer.close(index);
                                }
                                // formData.append("stuName", $("#stuName").val());
                                // formData.append("stuAge", $("#stuAge").val());
                                
                            }
                        });
                    break;
                    // case 'advertisementDel':
                    //     layer.msg('删除');
                    // break;
                };
            });

            table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
                if(layEvent === 'advertisementUpdate'){
                    $("#imgPath").val('')
                    $("#advertisement_name").val('')
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-rim', //加上边框
                        area: ['500px', '300px'], //宽高
                        title: '广告信息修改',
                        btn: ['更新','取消'],
                        content: $('#advertisementUpdate'),
                        yes: function(index){
                            // console.log($("#advertisement_name").val())
                            // var advertisement_name = $("#advertisement_name").val()
                            var file = $("#imgPath")[0].files[0];//获取文件
                            var formData = new FormData();
                            formData.append("picture", file);
                            formData.append("advertisement_name", $("#advertisement_name").val());
                            $.ajax({
                                type: "post",
                                url: "/admin/advertisement/updateAdvertisement?advertisementId=" +data.id,
                                data: formData,
                                dataType: "json",
                                processData: false,
                                contentType: false,
                                success: function(mag){
                                    layer.msg(mag.message)
                                    table.reload('adTest')
                                }
                            })
                            layer.close(index);
                            
                        }
                    });
                } else if(layEvent === 'advertisementDel'){ //删除
                    layer.confirm('真的删除行么', function(index){
                        $.ajax({
                            type: "post",
                            url: "/admin/advertisement/deleteAdvertisement",
                            data: {advertisementId: data.id},
                            dataType: "json",
                            success: function(mag){
                                layer.msg(mag.message)
                                if (mag.success == true) {
                                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                                    table.reload('adTest')
                                    layer.close(index);
                                }
                            }
                        })
                        
                    });
                } else if(layEvent === 'advertisementDelStatus'){ //编辑
                    if (data.status == 0) {
                        layer.confirm('下架该广告', function(index){
                            $.ajax({
                                type: "post",
                                url: "/admin/advertisement/changeShelf",
                                data: {advertisementId: data.id,action: 'stop'},
                                dataType: "json",
                                success: function(mag){
                                    layer.msg(mag.message)
                                    if (mag.success == true) {
                                        obj.update({
                                            status: '1'
                                        });
                                        layer.close(index);
                                    }
                                }
                            })
                            
                        });
                    }else {
                        layer.confirm('上架该广告', function(index){
                            $.ajax({
                                type: "post",
                                url: "/admin/advertisement/changeShelf",
                                data: {advertisementId: data.id,action: 'start'},
                                dataType: "json",
                                success: function(mag){
                                    layer.msg(mag.message)
                                    if (mag.success == true) {
                                        obj.update({
                                            status: '0'
                                        });
                                        layer.close(index);
                                    }
                                }
                            })
                            
                        });
                    }
                    
                }
            });


        });
        function adStatus(num) {
            if (num == 0) {
                var status = '正常'
            }else {
                var status = '未上架'
            }
            return status
        }

        function MillisecondToDate(msd) {
            
            var time = parseFloat(msd) / 1000;   //先将毫秒转化成秒
            if (msd == null || msd == undefined || msd == 0) {
                time = 0
            }else  {
                // time = parseInt(time / 86400) +"天" + parseInt((parseFloat(time / 86400.0) -parseInt(time / 86400.0)) * 60) + "小时" + parseInt((parseFloat((parseFloat(time / 86400.0) - parseInt(time / 86400.0)) * 60) - parseInt((parseFloat(time / 86400.0) - parseInt(time / 86400.0)) * 60)) * 60) + "分钟" + time + "秒";
                var days,hours,minutes,seconds, timesFormat = parseFloat(time / 86400.0);
                days = parseInt(time / 86400);
                hours = parseInt((timesFormat -days) * 60);
                minutes = parseInt((parseFloat((timesFormat - days) * 60) - hours) * 60);
                seconds = parseInt(parseFloat(((parseFloat((timesFormat - days) * 60) - hours) * 60) - minutes) * 60);

                time = days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
            }
            return time; 
        }
    </script>
</body>
</html>